package com.cloudcms.web.handler;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cloudcms.web.common.BusinessException;
import com.cloudcms.web.annotation.SessionId;
import com.cloudcms.web.util.Constants;
import com.cloudcms.web.util.CommUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

/**
 *
 * @author lv
 *
 */
@Service
public class SessionIdHandle implements HandlerMethodArgumentResolver {
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		if (parameter.getParameterType().isAssignableFrom(String.class)
				&& parameter.hasParameterAnnotation(SessionId.class)) {
			return true;
		}
		return false;
	}

	@Override
	public String resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
								  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		SessionId info = parameter.getParameterAnnotation(SessionId.class);
		if (info != null) {
			HttpServletRequest request = (HttpServletRequest) webRequest.getNativeRequest();
			HttpServletResponse response = (HttpServletResponse) webRequest.getNativeResponse();

			Cookie[] cookies = request.getCookies();

			String sessionid = "";
			if (cookies != null && cookies.length > 0) {
				for (Cookie c : cookies) {
					if (Constants.COOKIEPREFIX.equals(c.getName())) {
						sessionid = c.getValue();
						break;
					}
				}
			}

			if (StringUtils.isEmpty(sessionid)) {
				sessionid = CommUtil.generateToken(request);

				Cookie cookie = new Cookie(Constants.COOKIEPREFIX, sessionid);
				cookie.setPath("/");
				cookie.setHttpOnly(true);

				response.addCookie(cookie);
			}
			return sessionid;
		} else {
			throw new BusinessException(Constants.SIMPLE_RESULT_SYSTEM,"获取SessionId失败");
		}
	}
}
